from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View
from myapp.models import *
from mydjango import settings


from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
# from dwebsocket.decorators import accept_websocket
# import uuid

#获取当前时间
from django.utils import  timezone

#导入七牛密钥接口
from qiniu import Auth, put_file

#导入序列化类
from myapp.myser import *


#返回用户信息
class UserList(APIView):

    def get(self,request):
        #获取参数
        uid = request.GET.get('uid')
        print(uid)

        user = User.objects.filter(id=uid).all()

        ser = UserSer1(user,many=True).data

        return Response({'message':ser})







#用户更新接口
class UpdateUser(APIView):
    #序列化用户信息给 前端
    def get(self,request):
        res = {}
        #获取参数
        uid = request.GET.get('uid')
        print(uid)
        #查找用户
        user = User.objects.filter(id=uid).all()
        #序列化
        ser  = UpdateUserSerializerGet(instance=user,many=True)
        # print(ser)  UpdateUserSerializerGet(instance=<QuerySet [<User: User object (4)>]>, many=True):
        #     img = CharField(max_length=200)

        # print(ser.data) [OrderedDict([('img', '11111')])]
        res['data'] = ser.data
        return Response(res)


    #用户信息更新
    def patch(self,reqeust):
        res = {}
        #接收参数
        print(reqeust.data)
        uid = reqeust.data.get('uid')

        #查找用户
        user = User.objects.get(id=uid)

        #instance是要被修改的对象,有这个参数就是修改,没有就是增加
        #参与反序列化校验的数据信息
        #partial默认就是False,意思是每个必须字段都要有,也就是整体改,反之是局部改
        ser = UpdateUserSerializer(instance=user,data=reqeust.data,partial=True)
        print(ser)
        #UpdateUserSerializer(data=<QueryDict: {'img': ['11111'], 'password': ['123456789'], 'uid': ['4']}>, instance=<User: User object (4)>, partial=True):
        # password = CharField(max_length=200)
        # img = CharField(max_length=200)

        #验证
        if ser.is_valid():
            res['code'] = 200
            #保存
            ser.save()
        else:
            res['code'] = 400
            res['errors'] = ser.errors

        return Response(res)


## 保存图片到七牛云
class QiNiu(APIView):
    def get(self,reqeust):
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'EKA0JScb-UoPYpBND3gyql5zhC8c6A9IPTBVMueP'
        secret_key = 'kc16hFIGl_jqWRMDvSsc0ezMpsTVVxIgYMTMa0MB'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'md2020'
        # 上传后保存的文件名
        key = None   #不指定文件名
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, key, 3600)
        return  Response({'uptoken':token})



#上传文件
class  UploadFile(View):
    def post(self, request):
        #接受文件
        myfile = request.FILES.get('file')
        # 重复图片名 不能覆盖
        # 获取当前日期时间
        time_now = timezone.now()
        # print(time_now)  #2020-02-24 04:20:21.342873+00:00 需要用MD5编码

        #使用MD5编码
        m = hashlib.md5()
        #给当前时间编码
        m.update(str(time_now).encode())
        time_now = m.hexdigest()
        # print(time_now)  #482c96a1a64705ae6eefe4b562629be4

        #建立文件流对象
        # 用法os.path.join  函数功能：连接两个或更多的路径名组件  ，如果最后一个组件为空，则生成的路径以一个’ / ’分隔符结尾
        # 如果各组件名首字母不包含’ / ’，则函数会自动加上
        # 如果有一个组件是一个绝对路径，则在它之前的所有组件均会被舍弃
        #windows 有时候上传中文图片会报错  （如路径）修改加 str(replase（”‘’“）（‘’）)
        f = open(os.path.join(UPLOAD_ROOT,'',time_now + myfile.name),'wb')
        #进行写入文件
        for chunk in myfile.chunks():
            f.write(chunk)
        #关闭文件流
        f.close()

        #判断文件类型
        return HttpResponse(json.dumps({'filename':time_now +  myfile.name},ensure_ascii=False) ,content_type='application/json')





#定义地址和端口
host = '127.0.0.1'
port = '6379'

#简历redis连接
r = redis.Redis(host=host,port=port)

#定义验证码
class Mycode(View):
    #定义随机验证颜色
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        return (R,G,B)

    #随机验证码
    def get(self,request):
        #画布  #定义大写
        img_size = (110,50)
        #定义颜色   获取一个Image对象，参数分别是RGB模式。宽110，高50，白色
        image = Image.new("RGB",img_size,'white')
        #画笔   获取一个画笔对象，将图片对象传过去
        draw = ImageDraw.Draw(image,"RGB")
        #定义随机字符串
        source = "0123456789"
        #容器，用来接收随机字符串
        code_str = ""
        for i in range(4):
            #获取字体颜色
            text_color = self.get_random_color()
            #获取字符串
            tmp_num =random.randrange(len(source))
            #获取字符集
            random_str = source[tmp_num]
            #添加到容器中
            code_str += random_str
            #绘制  在图片上写东西，参数是：定位，字符串，颜色，字体
            draw.text((10+30*i,20),random_str,text_color)
        #文件流缓存区
        buf = io.BytesIO()
        #将图片保存到缓冲区
        image.save(buf,'png')
        #将随机码存储到redis中
        r.set('code',code_str)
        # 保存在session里
        request.session['session_code'] = code_str
        print(request.session.get('session_code'))
        return HttpResponse(buf.getvalue(),'image/png')




#md5 加密方法
def make_password(mypass):
    #生成md5对象
    md5 = hashlib.md5()
    #定义加密对象
    sign_str = mypass
    #转码
    sign_utf8 = str(sign_str).encode(encoding='utf-8')
    #加密操作
    md5.update(sign_utf8)
    #生成密文
    md5_server = md5.hexdigest()
    return md5_server


#注册接口
class Register(APIView):
    def get(self,reqeust):
        username =reqeust.GET.get('username','未收到用户名')
        password =reqeust.GET.get('password','未收到密码')
        code =reqeust.GET.get('code','未收到验证码')

        # 从reids获取验证码
        mycode = r.get('code')
        #转码
        mycode = mycode.decode('utf-8')
        print('-'*20,mycode)
        session_code = reqeust.session.get('session_code')
        print('='*20,session_code)
        if code !=mycode:
            res = {}
            res['code'] = 405
            res['message'] = '验证码输入错误'
            return Response(res)

        # 排重操作
        user = User.objects.filter(username=username).first()
        if user:
            res = {}
            res['code'] = 405
            res['message'] = '用户已经存在'
            return Response(res)

        # 进行入库操作
        user = User(username=username, password=make_password(password), img='', type=0)
        # 保存
        user.save()

        # 返回结果
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)



class Login(APIView):
    def get(self,request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        # code = request.GET.get('code')
        find_user = User.objects.filter(username=username,password=make_password(password)).first()
        # print(find_user)
        # print(find_user.username)
        # print(find_user.password)

        #判断用户名
        if find_user:
            res = {}
            res['code'] = 200
            res['message'] = '登陆成功'
            res['username'] = find_user.username
            res['uid'] = find_user.id
            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或密码错误'
            return Response(res)




#微博登录
import requests

def WB_token(request):
    #获取code
    code = request.GET.get('code')
    print(code)

    #换取网址
    url = 'https://api.weibo.com/oauth2/access_token'

    #发送请求进行换取
    resp = requests.post(url,{"client_id": '3405127097',
        "client_secret": "b36bb4710180afa217486b8d7d00cce5",
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/wbtoken/"})

    print(resp.json())
    # 获取访问令牌  以及 uid
    access_token = resp.json()['access_token']
    uid = resp.json()['uid']

    #查找微博是否是第一次登录
    user = User.objects.filter(username=str(resp.json()['uid'])).first()

    #创建两个容器
    sinl = ""
    uid = ""
    if  user:
        sinl = user.username
        uid = user.id
    else:
        #如果不存在创建新用户
        user= User(username=str(resp.json()['uid']),password='',type=0)
        #保存
        user.save()

        #查找参数
        nuser = User.objects.filter(username=str(resp.json()['uid'])).first()

        sinl = nuser.username
        uid = nuser.id

    # print(sinl)
    # print(uid)

    #跳转到首页 并传参 uid  and sinl_id
    return redirect('http://localhost:8080/?sinl='+str(sinl)+'&uid='+str(uid))







#钉钉登录
import time
import hmac
import base64
from hashlib import sha256
import urllib
import json

#构造钉钉回调方法
def dd_back(request):

    #获取code
    code = request.GET.get("code")

    t = time.time()
    #时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret ='h8XtQN8zIPBGNFOm8-ceIjGha1bMuwU97cmJxne3bZ9J_JjA9JUZIPvS7oatW4QN'
    #构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
    #请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='
                        +urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="
                        +timestamp+"&accessKey=dingoaozqcikkdml2pbzx8",data=json.dumps(payload)
                        ,headers=headers)

    res_dict = json.loads(res.text)
    # print(res_dict)
    # print(res_dict['user_info']['nick'])


    user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

    dduser = ""
    uid = ""
    # 判断是否是第一次登录
    if user:
        dduser = user.username
        uid = user.id
    else:
        #创建
        user = User(username=str(res_dict['user_info']['nick']),password="",type=0)
        #保存
        user.save()
        #重写查找
        nuser = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
        dduser = nuser.username
        uid = nuser.id


    return redirect("http://localhost:8080/?dduser="+str(dduser)+'&uid='+str(uid))

































